package com.example.fence.service.impl;


import com.example.fence.Task;

import com.example.fence.entity.Fence;
import com.example.fence.util.FenceDetectUtil;
import com.example.fence.util.FenceStoreUtil;
import com.example.fence.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.fence.util.FenceStoreUtil.imeiLock;
import static com.example.fence.util.ResultCode.SUCCESS;
import static java.lang.Enum.valueOf;

/**
 * 电子围栏功能实现类，业务逻辑在此完成
 */
@Service
@Slf4j
public class ElectricFenceServiceImpl {
    /**
     * 创建电子围栏功能
     * @param fence 电子围栏信息
     * @return Result类包含设置结果
     */

    public Result createFence(Fence fence) throws MqttException {

        // 具体的业务逻辑代码
        log.info("creating Fence...");
        // 测试
//        Boolean flag= FenceDetectUtil.PoiInPoly(fence.getPointList(),"120.158917,30.29928");

        // 将数据存到在线表
        for(String device:fence.getDevices()){  // imei-pointList
            log.info("device added!"+device+":"+fence.getPointList().toString());
            FenceStoreUtil.imeiToPointList.put(device,fence.getPointList());
            if (FenceStoreUtil.imeiLock.containsKey(device) && FenceStoreUtil.imeiLock.get(device)) {
                FenceStoreUtil.imeiLock.put(device, false);
                Task.PostUnC2(device);
            }

        }

        // 将数据上传TB数据库
        for(String device:fence.getDevices()){  // imei-pointList
            //log.info("device added!"+device+":"+fence.getPointList().toString());
            Task.PostFence(device,fence.getPointList());
        }

        // 将数据存到fence列表
        if(FenceStoreUtil.fenceDeviceList.containsKey(fence.getPointList())){
            log.info("Fence Existed!"+fence.getPointList().toString());
            FenceStoreUtil.fenceDeviceList.get(fence.getPointList()).addAll(fence.getDevices());
        }
        return new Result(SUCCESS.code, true, fence, "success");  // 瞎写的测试用
    }

    public Result getFence(String imei){
        Map<String,Object> resultMap=new HashMap<>();
        // 获取设备电子围栏信息，涉及imeiToPointList表，通过imei获取path

        resultMap.put("imei",imei);
        resultMap.put("path",FenceStoreUtil.imeiToPointList.get(imei)); // 获取在线表的最新路径信息

        return new Result(SUCCESS.code, true, resultMap, "success");
    }

    public Result updateFence(Fence fence){

        // 具体的业务逻辑代码
        log.info("updating Fence...");


        return new Result(SUCCESS.code, true, fence, "success");  // 瞎写的测试用
    }



}

